import logging

from flask import Blueprint, request, render_template

from app.config.config import config
from app.settings import env
from model.article import Article

index=Blueprint('index',__name__)
#对应前端显示分类的字典
label_types={
    "recommend":{"name":"推荐","delected":"selected"},
    "auto_test":{"name":"自动化测试","selected":"no-selected"},
    "python": {"name": "自动化测试", "selected": "no-selected"},
    "java": {"name": "自动化测试", "selected": "no-selected"},
    "function": {"name": "自动化测试", "selected": "no-selected"},
    "per_test": {"name": "自动化测试", "selected": "no-selected"},
    "funny": {"name": "自动化测试", "selected": "no-selected"},
}
@index.route('/')
def home():
    #获取当前是第几页
    page=request.args.get('page')
    article_type=request.args.get('article_type')
    logging.debug("page:"+str(page))
    logging.debug("article_type:"+str(article_type))

    if page is None:
        page=1
    if article_type is None:
        article_type="recommend"
    #到数据库中查询文章的数据，返回给前端的页面
    article=Article()
    #文章搜索功能实现
    search_keyword=request.args.get('keyword')
    if search_keyword is None:
        db_result=article.search_article(page,search_keyword)
    else:
        db_result=article.find_article(page,article_type)
    for article,nickname in db_result:
        #分类内容显示转换
        article.label=label_types(article.label_name).get("name")
        #日期显示
        article.create_time=str(article.create_time.month)+'.'+str(article.create_time.day)+'.'+str(article.create_time.hour)
        #图片路径处理 "/images/article/header"
        article.article_image=config[env].article_header_image_path+str(article.article_image)
        #文章标签格式的修改
        article.article_tag=article.article_tag.replace(","," . ")
    stat_num=request.args.get('stat_num')
    if stat_num is None:
        stat_num=0
    end_num=len(db_result)

    #左侧菜单文章分类的逻辑
    for k,v in label_types.items():
        if article_type == k:
            v["selected"]="selected"
        else:
            v["selected"]="no-selected"

    return render_template("index.html",result=db_result,stat_num=stat_num,end_num=end_num,label_types=label_types)